package com.santy.xxljob.jobhandler;

import com.santy.xxljob.config.XxlJobConfig;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.IntStream;

/**
 * Description: 多机分片处理
 * Datetime: 2021/1/11-16:05
 * Author: Santy
 */
@Component
public class MultiMachineMultiTasks {

    private static final Logger logger = LoggerFactory.getLogger(MultiMachineMultiTasks.class);

    //城市编号
    private static final List<Integer> CITY_ID_LIST = Arrays.asList(550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 561, 562, 563, 564, 566);

    //每个城市的任务数
    private static final int PER_LATN_TASK_NUM = 30;

    // 任务数据库
    private static final Map<Integer, List<String>> singleMachineMultiTasks;

    static {
        singleMachineMultiTasks = new HashMap<>();
        CITY_ID_LIST.forEach(city -> {
            List<String> tasks = new ArrayList<>(PER_LATN_TASK_NUM);
            IntStream.rangeClosed(1, PER_LATN_TASK_NUM).forEach(index -> {
                String orderInfo = city + "------NO." + index ;
                tasks.add(orderInfo);
            });

            singleMachineMultiTasks.put(city, tasks);
        });
    }

    /**
     * @Description: 多机分片处理
     * @param params:
     * @author: Santy
     * @Datetime: 2021/1/11 16:28
     */
    @XxlJob(value = "multiMachineMultiTasks", init = "init", destroy = "destroy")
    public ReturnT<String> multiMachineMultiTasks(String params) throws Exception {

        // 此处的shardingVO值是注册的时候添加到xxl-job-admin的，无法手动添加
        ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
        int n = shardingVO.getTotal(); // n 个实例
        int i = shardingVO.getIndex(); // 当前为第i个


        // 2.3 版本之后的
//        int n = XxlJobHelper.getShardTotal(); // n 个实例
//        int i = XxlJobHelper.getShardIndex(); // 当前为第i个

        IntStream.range(0, CITY_ID_LIST.size()).forEach(cityIndex -> {
            if (cityIndex % n == i) {
                int city = CITY_ID_LIST.get(cityIndex);
                List<String> tasks = singleMachineMultiTasks.get(city);
                Optional.ofNullable(tasks).ifPresent(todoTasks -> {
                    todoTasks.forEach(task -> {
                        XxlJobLogger.log("实例【{}】执行【{}】，任务内容为：{}", i, city, task);
                        System.out.println("实例【"+i+"】执行【"+city+"】，任务内容为：" + task);
                    });

                });
            }
        });
        return ReturnT.SUCCESS;
    }


    public void init() {
        logger.info("======init======");
    }

    public void destroy() {
        logger.info("======destory======");
    }
}
